<template>
  <div class="xtx-form">
    <div class="user-info">
      <img :src="avatar" alt="" />
      <p>Hi，{{nickname}}欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <input v-model="form.mobile" class="input" type="text" placeholder="绑定的手机号" />
      </div>
      <div class="error"></div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <input v-model="form.code" class="input" type="text" placeholder="短信验证码" />
        <span class="code" @click="sendCode">发送验证码</span>
      </div>
      <div class="error"></div>
    </div>
    <a href="javascript:;" class="submit" @click="handleBind">立即绑定</a>
  </div>
</template>

<script>
import { userQQBindCode } from '@/api/user'
import { getCurrentInstance, reactive } from 'vue-demi'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackBind',
  props: {
    nickname: {
      type: String,
      default: ''
    },
    avatar: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    const instance = getCurrentInstance()
    const store = useStore()
    const router = useRouter()
    // 表单数据
    const form = reactive({
      mobile: '',
      code: ''
    })
    // 发送验证码
    const sendCode = async () => {
      try {
        const ret = await userQQBindCode(form.mobile)
        if (ret.msg === '操作成功') {
          // 发送成功
          instance.proxy.$message({
            type: 'success',
            text: '发送验证码成功'
          })
        }
      } catch {
        instance.proxy.$message({
          type: 'error',
          text: '发送验证码失败'
        })
      }
    }

    // 绑定手机号提交表单
    const handleBind = async () => {
      const ret = await store.dispatch('user/bindMobile', {
        unionId: props.unionId,
        ...form
      })
      if (ret) {
        // 绑定成功
        instance.proxy.$message({
          type: 'success',
          text: '绑定成功'
        })
        // 跳转到主页面
        router.push('/')
      } else {
        // 绑定失败
        instance.proxy.$message({
          type: 'error',
          text: '绑定失败'
        })
      }
    }
    return { sendCode, form, handleBind }
  }
}
</script>

<style scoped lang='less'>
.user-info {
  width: 320px;
  height: 70px;
  margin: 0 auto;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 25px;
  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }
  p {
    padding-left: 10px;
  }
}
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
